package com.lemon.smartsafety.ui.fragment.fire.situation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.fire.FireInspectionRefresh;
import com.lemon.smartsafety.file.MySPUtilsName;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.interfac.FinishCallBack;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.DeviceSResult;
import com.lemon.smartsafety.result.fire.FireInspectionItem;
import com.lemon.smartsafety.result.fire.FireListMode;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseFragment;
import com.lemon.smartsafety.ui.activity.fire.item.inspection.FireInspectionProjectActivity;
import com.lemon.smartsafety.ui.activity.fire.item.inspection.FirefightingCompanyAddressActivity;
import com.lemon.smartsafety.ui.adapter.fire.FireSituationDeviceAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/9/7 13:44
 * 修改人：Fargo
 * 修改时间：2016/9/7 13:44
 * 修改备注：
 */
public class DeviceSFragment extends NewBaseFragment {
    @Bind(R.id.listView)
    ListRefreshView listView;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private SuperviseCompanyResult.ResultEntity resultEntity;
    private FireListMode fireListMode;
    private List<DeviceSResult> mList;
    private List<DeviceSResult> deviceSResultList;


    private FireSituationDeviceAdapter fireSituationDeviceAdapter;


    //0全部  1完好  2故障
    private int mTAG = -1;
    private String check_type = "";
    private int mTagWidth = 0;

    private FireInspectionItem fireInspectionItem;

    @Override
    protected void getBundleArgs() {
        if (getArguments().containsKey(BundleKey.FIRE_COMPANY_BASE_INFO)) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getArguments().getSerializable(BundleKey.FIRE_COMPANY_BASE_INFO);
            fireListMode = (FireListMode) getArguments().getSerializable(BundleKey.FIRE_PERSONAL_DATA);
            mTAG = getArguments().getInt(BundleKey.FIRE_PERSONAL_S);
            check_type = getArguments().getString(BundleKey.FIRE_CHECK_TYPE);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_s_device;
    }

    @Override
    protected void initView() {
        LogUtils.LOGE("初始化" + mTAG);


        mList = new ArrayList<>();
        fireSituationDeviceAdapter = new FireSituationDeviceAdapter(mActivity, mList);
        listView.setAdapter(fireSituationDeviceAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {

                openAddress(new FinishCallBack() {
                    @Override
                    public void callBackFunction(boolean isOk) {
                        if(isOk){
                            fireInspectionItem = new FireInspectionItem();
                            fireInspectionItem.setItemId(mList.get(position).getItemId());
                            fireInspectionItem.setIsPatrol(mList.get(position).getIsPatrol());
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(BundleKey.FIRE_INSPECTION_BUILD_ITEM_DATA, fireInspectionItem);
                            bundle.putString(BundleKey.FIRE_CHECK_TYPE_ITEM, mList.get(position).getPosition());
                            bundle.putString(BundleKey.FIRE_CHECK_TYPE_ITEM_TAG, String.valueOf(mTAG));

                            UIHelper.showActivity(mActivity, bundle, FireInspectionProjectActivity.class);
                        }
                    }
                });

            }
        });
        initSwipRefresh(swipeLayout);
        initLoadeRefresh(listView);


        if (mTAG == 0) {
            LogUtils.LOGE("开始初始化");
            initList();
        }

        try {
            if ((int) MySPUtilsName.getSP(MySPUtilsName.GET_WIDTH, 0) != 0) {
                if (fireSituationDeviceAdapter.getmTAGgetWidth() == 0) {
                    mTagWidth = (int) MySPUtilsName.getSP(MySPUtilsName.GET_WIDTH, 0);
                    fireSituationDeviceAdapter.setmTAGgetWidth(mTagWidth);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Subscribe
    public void onEventMainThread(RefreshViewEntity refreshViewEntity) {
        //刷新View
        if (refreshViewEntity.getTAG().equals(DeviceSFragment.class.getName())) {
            if (refreshViewEntity.getData().equals(String.valueOf(mTAG))) {
                LogUtils.LOGE("初始化推送" + refreshViewEntity.getData());
                initList();
              /*  if (CommonUtil.listIsEmpty(mList)) {
                    initList();
                }*/
            }
        }
   /*     else if (refreshViewEntity.getTAG().equals("GET_WIDTH")){
            if (fireSituationDeviceAdapter.getmTAGgetWidth() == 0) {
                mTagWidth = viewTag.getLineTag().getWidth();
                fireSituationDeviceAdapter.setmTAGgetWidth(mTagWidth);
                viewTag.setVisibility(View.GONE);
            }
        }*/
    }

    @Subscribe
    public void onEventMainThread(FireInspectionRefresh refreshViewEntity) {
        //刷新View
        if (refreshViewEntity.getData().equals(String.valueOf(mTAG))) {

            LogUtils.LOGE("检查完刷新页面" + refreshViewEntity.getData());

            initList();

        }

    }

    /**
     * 错误的情况下 刷新
     */
    public void errorView(String title) {

        try {
            if (CommonUtil.listIsEmpty(mList)) {
                viewFireCompanyNone.setVisibility(View.VISIBLE);
                showSwipLayout(swipeLayout,false);

                viewFireCompanyNone.setTxt_imgVisible(false);
                if (CommonUtil.strIsEmpty(title)) {
                    viewFireCompanyNone.setContent("没有更多数据");
                    viewFireCompanyNone.setSearch("重试");
                } else {
                    viewFireCompanyNone.setContent(title);
                    viewFireCompanyNone.setSearch("重试");
                }
                viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                    @Override
                    public void click() {
                        initList();
                    }
                });
            } else {
                viewFireCompanyNone.setVisibility(View.GONE);
                showSwipLayout(swipeLayout,true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void initHttp() {

    }

    @Override
    protected void initList() {
        listView.setIsload(true);
        current_page = 1;
        httpList();
    }

    @Override
    protected void loadList() {
        if (mList.size() % page_size == 0) {
            current_page = current_page + 1;
            httpList();
        } else {
            showUpLoad(false, listView);
            listView.setIsload(false);
            ToastUtil.show("没有更多数据了");
        }
    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {

    }


    private void httpList() {
        if (!bPutHttp) {
            bPutHttp = true;
            LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
            params.put("page_size", String.valueOf(page_size));
            params.put("current_page", String.valueOf(current_page));


            params.put("check_type", check_type);
            params.put("company_code", resultEntity.getCompanyCode());
            params.put("type_code", fireListMode.getTypeCode());
            params.put("is_intact", String.valueOf(mTAG + 1));


            showLoading("");
            HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_intact_detail_item_new), "", new HttpOkBase.HttpInterface() {
                @Override
                public void callBackFunction(boolean httpClient, String result) {

                    dismissLoading();
                    bPutHttp = false;
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {

                                try {
                                    deviceSResultList = mGson.fromJson(mGson.toJson(baseMode.getResult()), new TypeToken<List<DeviceSResult>>() {
                                    }.getType());
                                    transList();

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } else {
                                if(baseMode.getCode().equals("1002")){
                                    if(current_page==1){
                                        mList.clear();
                                    }
                                }

                                strShowMsg = baseMode.getMsg();
                                handler.sendEmptyMessage(SHOW_MSG);
                                errorView(strShowMsg);
                            }
                            //fireSituationDeviceAdapter.notifyDataSetChanged();
                        }
                    }else{
                        deviceSResultList=null;
                        errorView("网络连接失败");
                    }
                }
            });
        }

    }


    /**
     * 转换list
     */
    private void transList() {

        if (current_page == 1) {
            mList.clear();
        }
        mList.addAll(deviceSResultList);
        fireSituationDeviceAdapter.notifyDataSetChanged();
        errorView("");
    }




    private void openAddress(final FinishCallBack finishCallBack) {

        //点击现场检查
        locationUtil.getLoacation(new LocationUtil.CallBackInterface() {
            @Override
            public void callBackFunction() {
                LogUtils.LOGE("定位地理位置");
                signHttp(new FinishCallBack() {
                    @Override
                    public void callBackFunction(boolean isOk) {
                        if (isOk) {
                            finishCallBack.callBackFunction(true);
                        }
                    }
                });
            }
        });


    }


    /**
     * 监督签到 是否允许现场检查
     */
    public void signHttp(final FinishCallBack finishCallBack) {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("latitude", locationUtil.getmLat());
        params.put("longitude", locationUtil.getmLng());
        params.put("position", locationUtil.getmAddress());

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Sign_in), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            //可以进行现场检查
                            finishCallBack.callBackFunction(true);
                        } else {
                            if (baseMode.getCode().equals("2000")) {
                                openCompanyAddress(baseMode);
                            } else {
                                ToastUtil.show(baseMode.getMsg());
                            }
                            finishCallBack.callBackFunction(false);
                        }
                    } else {
                        finishCallBack.callBackFunction(false);
                    }
                } else {
                    finishCallBack.callBackFunction(false);
                }
            }
        });

    }


    /**
     * 提示用户完善定位信息
     *
     * @param baseMode
     */
    private void openCompanyAddress(BaseMode baseMode) {

        getConfirmDialog(baseMode.getMsg(), R.string.fire_location_sure, R.string.fire_location_cancel, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    //添加
                    Intent intent = new Intent(mActivity, FirefightingCompanyAddressActivity.class);
                    bundle = new Bundle();
                    bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            }
        }).show();
    }



}
